package com.grz.controller;

import com.grz.core.HasUsername;
import com.grz.core.Result;
import com.grz.domain.Book;
import com.grz.service.IBookService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@AllArgsConstructor
@RequestMapping("/book")
public class BookController {

    private final IBookService bookService;

    @PostMapping
    public Result<Integer> insert(@RequestBody Book book){
        // 插入之前，需要做参数校验
        return Result.success(bookService.insert(book));
    }

    // 自定义规则：是admin用户才能修改Book
    @HasUsername(value = "admin")
    @PutMapping
    public Result<Integer> update(@RequestBody Book book) {
        if (book.getId() == null) {
            return Result.error(400, "请传入id的参数");
        }
        return Result.success(bookService.update(book));
    }

    @DeleteMapping
    public Result<Integer> delete(int id) {
        return Result.success(bookService.delete(id));
    }

    @GetMapping("/{id}")
    public Result<Book> selectById(@PathVariable int id) {
        int i = 1 / 0;
        return Result.success(bookService.selectById(id));
    }

    /**
     * 根据 type精准匹配，根据name模糊匹配
     * @param book 查询条件
     * @return 匹配的列表
     */
    @PostMapping("/list")
    public Result<List<Book>> selectList(@RequestBody Book book) {
        return Result.success(bookService.selectList(book));
    }
}
